<script setup lang="ts">
import {
  reqAllSaleAttr,
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuSaleAttrList,
  reqAddOrUpdate,
} from '@/api/product/spu/index.ts'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
let emit = defineEmits(['changeScene'])
let spuParams = ref<any>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
})
const AllTradeMark = ref()
let imageList = ref()
let dialogVisible = ref(false)
let dialogImage = ref('')
let saleAttr = ref<any>([])
let allAttr = ref<any>([])
const saleAttrIdAndName = ref('')
const cancel = () => {
  emit('changeScene', { flag: 1, params: 'update' })
}
const init = async (row: any) => {
  spuParams.value = row
  let resTradeMark = await reqAllTradeMark()
  let resImageList = await reqSpuImageList(row.id)
  let resSaleAttrList = await reqSpuSaleAttrList(row.id)
  let allSaleAttr = await reqAllSaleAttr()
  AllTradeMark.value = resTradeMark.data
  imageList.value = resImageList.data.map((item: any) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  saleAttr.value = resSaleAttrList.data
  allAttr.value = allSaleAttr.data
}
const addInit = async (c3Id: number | string) => {
  Object.assign(spuParams.value, {
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  })
  imageList.value = []
  saleAttr.value = []
  saleAttrIdAndName.value = ''
  spuParams.value.id = ''

  spuParams.value.category3Id = c3Id
  let resTradeMark = await reqAllTradeMark()
  let allSaleAttr = await reqAllSaleAttr()
  AllTradeMark.value = resTradeMark.data
  allAttr.value = allSaleAttr.data
}

let unSelectSaleAttr = computed(() => {
  let newArr = allAttr.value.filter((item: any) => {
    return saleAttr.value.every((i: any) => {
      return i.saleAttrName != item.name
    })
  })
  return newArr
})
const handlePictureCardPreview = (file: any) => {
  dialogImage.value = file.url
  dialogVisible.value = true
}
const handlerUpload = (file: any) => {
  if (
    file.type == 'image/png' ||
    file.type == 'image/jpeg' ||
    file.type == 'image/webp' ||
    file.type == 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小不能大于3M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件类型要为png/jpeg/webp/gif',
    })
    return false
  }
}
const addAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndName.value.split(':')
  let newSaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  saleAttr.value.push(newSaleAttr)
  saleAttrIdAndName.value = ''
}
const toEdit = (row: any) => {
  row.flag = true
  row.saleAttrValue = ''
}
const toLook = (row: any) => {
  const { baseSaleAttrId, saleAttrValue } = row

  let newSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue,
  }
  let isName = row.spuSaleAttrValueList.find((item: any) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (saleAttrValue.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  if (isName) {
    ElMessage({
      type: 'error',
      message: '属性值重复',
    })
    return
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}
const save = async () => {
  let newImageList = imageList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  spuParams.value.spuImageList = newImageList
  spuParams.value.spuSaleAttrList = saleAttr
  console.log(spuParams.value.id)
  let res = await reqAddOrUpdate(spuParams.value)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: spuParams.value.id ? '更新成功' : '添加成功',
    })
    emit('changeScene', {
      flag: 1,
      params: spuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: spuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
defineExpose({
  init,
  addInit,
})
</script>

<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        v-model="spuParams.spuName"
        placeholder="请你输入SPU名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="spuParams.tmId">
        <el-option
          v-for="item in AllTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入SPU描述"
        v-model="spuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="imageList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-upload="handlerUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible" width="70%">
        <img
          :src="dialogImage"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="saleAttrIdAndName"
        :placeholder="
          unSelectSaleAttr.length > 0
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无'
        "
      >
        <el-option
          :value="`${item.id}:${item.name}`"
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 10px"
        type="primary"
        icon="Plus"
        plain
        :disabled="!unSelectSaleAttr.length"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #="{ row }">
            <el-tag
              style="margin: 0 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              closable
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              @blur="toLook(row)"
              v-model="row.saleAttrValue"
              v-if="row.flag == true"
              placeholder="请你输入属性值"
              size="small"
              style="width: 100px"
            ></el-input>
            <el-button
              v-else
              @click="toEdit(row)"
              type="primary"
              size="small"
              icon="Plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="saleAttr.splice(scope.$index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        :disabled="
          !spuParams.spuName && !spuParams.tmId && !spuParams.description
        "
        type="primary"
        @click="save"
      >
        保存
      </el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss"></style>
